/*
 * @(#)UpgradeAction.java
 * 2011-9-24 下午09:36:30
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.upgrade.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.struts2.convention.annotation.Namespace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.qyxx.platform.common.json.JsonOutput;
import com.qyxx.platform.common.module.web.CrudActionSupport;
import com.qyxx.platform.common.module.web.FormatMessage;
import com.qyxx.platform.common.module.web.Messages;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.common.utils.spring.SpringContextHolder;
import com.qyxx.platform.common.utils.web.struts2.Struts2Utils;
import com.qyxx.platform.gsc.GsParseUtils;
import com.qyxx.platform.gsc.utils.SystemParam;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.exception.GsException;
import com.qyxx.platform.sysmng.upgrade.entity.Upgrade;
import com.qyxx.platform.sysmng.upgrade.service.UpgradeManager;
import com.qyxx.platform.sysmng.utils.Constants;


/**
 *  系统升级模块管理
 *  
 *  @author gxj
 *  @version 1.0
 *  @since 1.6 2011-9-24 下午09:36:30
 */
@Namespace("/sys/upgrade")
public class UpgradeAction extends CrudActionSupport<Upgrade> {
	
	private static final long serialVersionUID = -3214199305972555680L;
	
	private static Logger logger = LoggerFactory.getLogger(UpgradeAction.class);
	
	private static SystemParam sp = SpringContextHolder.getBean("systemParam");

	private File filedata;
	
	private String filedataFileName = "";
	
	private String jwpName = "";
	
	private UpgradeManager upgradeManager;
	
	private Boolean isFullUpdate = false;//全量更新
	
	/**
	 * @return upgradeManager
	 */
	public UpgradeManager getUpgradeManager() {
		return upgradeManager;
	}


	
	/**
	 * @param upgradeManager
	 */
	@Autowired
	public void setUpgradeManager(UpgradeManager upgradeManager) {
		this.upgradeManager = upgradeManager;
	}


	/**
	 * @return filedata
	 */
	public File getFiledata() {
		return filedata;
	}

	
	/**
	 * @param filedata
	 */
	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	
	/**
	 * @return filedataFileName
	 */
	public String getFiledataFileName() {
		return filedataFileName;
	}

	
	/**
	 * @param filedataFileName
	 */
	public void setFiledataFileName(String filedataFileName) {
		this.filedataFileName = filedataFileName;
	}

	/**
	 * @return jwpName
	 */
	public String getJwpName() {
		return jwpName;
	}

	/**
	 * @param jwpName
	 */
	public void setJwpName(String jwpName) {
		this.jwpName = jwpName;
	}

	

	
	/**
	 * @return isFullUpdate
	 */
	public Boolean getIsFullUpdate() {
		return isFullUpdate;
	}



	
	/**
	 * @param isFullUpdate
	 */
	public void setIsFullUpdate(Boolean isFullUpdate) {
		this.isFullUpdate = isFullUpdate;
	}



	@Override
	public String list() throws Exception {
		return SUCCESS;
	}
	
	@JsonOutput
	public String queryList() throws Exception {
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
		pager = upgradeManager.searchUpgradeLog(pager, filters);
		Struts2Utils.renderJson(pager);
		return null;
	}

	@Override
	public String input() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@JsonOutput
	@Override
	public String save() throws Exception {
		String jwpPathName = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmssSSS");
		boolean vFlag = GsParseUtils.checkJwpVersion(jwpPathName, filedata, filedataFileName);
		if(vFlag) {
			upgradeJwp(jwpPathName, null, isFullUpdate);
		} else {
			//版本号不一致，需要提示
			FormatMessage fm = new FormatMessage();
			fm.setFlag(Messages.FAIL);
			fm.setMsg(jwpPathName);
			formatMessage.setMsg(fm);
		}
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 升级jwp
	 * 
	 * @param jwpPathName
	 * @param rollbackId 不为null表示重新部署
	 */
	private void upgradeJwp(String jwpPathName, Long rollbackId, Boolean isFullUpdate) {
		Upgrade upgradeLog = new Upgrade();
		upgradeLog.setDeployType(Upgrade.DEPLOY_TYPE_SYS);
		User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION_ID);
		upgradeLog.setLoginName(user.getLoginName());
		upgradeLog.setOrgName(user.getOrganizationName());
		upgradeLog.setRealName(user.getRealName());
		HttpServletRequest request = Struts2Utils.getRequest();
		upgradeLog.setIp(request.getRemoteAddr());
		upgradeLog.setMachineName(request.getRemoteHost());
		upgradeLog.setDeployUrl(jwpPathName);
		
		Date startDate = new Date();
		upgradeLog.setDeployTimeStart(startDate);
		try {
			if(null != rollbackId) {
				upgradeLog.setRollbackId(rollbackId);
			}
			String jwp = GsParseUtils.handleGs(jwpPathName, isFullUpdate);
			upgradeLog.setDeployName(jwp+(isFullUpdate?"【全量更新】":"【增量更新】"));
			upgradeLog.setDeployFlag(Upgrade.DEPLOY_FLAG_SUCCESS);
			formatMessage.setMsg(true);
		} catch(Exception e) {
			logger.error("部署jwp出现异常", e);
			String info = GsParseUtils.getStackTrace(e);
			formatMessage.setFlag(Messages.ERROR);
			formatMessage.setMsg(e.getMessage());
			upgradeLog.setDeployName((isFullUpdate?"【全量更新】":"【增量更新】"));
			upgradeLog.setDeployFlag(Upgrade.DEPLOY_FLAG_FAIL);
			upgradeLog.setExceptionLog(info);
		}
		Date endDate = new Date();
		upgradeLog.setDeployTimeEnd(endDate);
		upgradeManager.saveUpgradeLog(upgradeLog);
	}
	
	/**
	 * 强制升级
	 * 
	 * @return
	 * @throws Exception
	 */
	@JsonOutput
	public String forceUpgrade() throws Exception {
		upgradeJwp(jwpName, null, isFullUpdate);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	@JsonOutput
	public String switchJwp() throws Exception {
		Upgrade upgradeLog = upgradeManager.getUpgradeLog(id);
		if(null == upgradeLog) {
			throw new GsException("编号为" + id + "的部署日志不存在");
		}
		upgradeJwp(upgradeLog.getDeployUrl(), id, isFullUpdate);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}
	
	/**
	 * 导出Jwp文件
	 * 
	 * @return
	 * @throws Exception
	 */
	public String exportJwp() throws Exception {
		boolean isInline = false;
		String jwpFileName = GsParseUtils.zipGsFile(jwpName);
		String filePath = sp.getUploadFilePath() + com.qyxx.platform.gsc.utils.Constants.GS_PACKAGE_PATH + jwpFileName;
		Struts2Utils.writeFile(jwpFileName, filePath, isInline);
		return null;
	}
	
	@JsonOutput
	@Override
	public String view() throws Exception {
		formatMessage.setMsg(entity);
		Struts2Utils.renderJson(formatMessage);
		return null;
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		try {
			if (id != null) {
				entity = upgradeManager.getUpgradeLog(id);
			} else {
				entity = new Upgrade();
			}	
		} catch(Exception e) {
			logger.error("", e);
		}
	}

}
